package cn.android666.settimedemo

import android.content.Intent
import android.icu.util.Calendar
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.Settings
import android.text.format.DateFormat
import cn.android666.settimedemo.databinding.ActivityMainBinding
import cn.dazhou.ok_http_util.OkHttpClientBuilder
import com.evendai.loglibrary.Timber
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Request
import okhttp3.Response
import org.jetbrains.anko.startActivityForResult
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(), Handler.Callback {

    private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val handler: Handler = Handler(Looper.getMainLooper(), this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.autoDateAndTimeCheckBox.setOnCheckedChangeListener { _, isChecked -> TimeUtil.setDateTimeAuto(this, isChecked) }
        binding.autoTimeZoneTimeCheckBox.setOnCheckedChangeListener { _, isChecked -> TimeUtil.setTimeZoneAuto(this, isChecked) }
        binding.use24HourCheckBox.setOnCheckedChangeListener { _, isChecked -> TimeUtil.set24HourFormat(this, isChecked) }
        binding.setDateButton.setOnClickListener { TimeUtil.setDate(this, 1970, 11, 31) }
        binding.setTimeButton.setOnClickListener { TimeUtil.setTime(this, 12, 30) }
        binding.setTimeZoneButton.setOnClickListener { TimeUtil.setTimeZone(this, "Asia/Seoul") }
        binding.setUseNetTimeButton.setOnClickListener {
            thread {
                val url = "https://www.baidu.com" // 在新球中这个百度链接访问不到，报异常如下，不知道是什么原因，有时间需要解决一下：
                // A connection to https://www.baidu.com/ was leaked. Did you forget to close a response body?
                // To see where this was allocated, set the OkHttpClient logger level to FINE: Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);
//                val url = "https://10.238.113.50"
                val okHttpClient = OkHttpClientBuilder.createOkHttpClientBuilder()
                    .addInterceptor(TimeSynchronizationInterceptor())
                    .callTimeout(1, TimeUnit.SECONDS)
                    .build()
                okHttpClient.newCall(Request.Builder().url(url).build()).enqueue(object: Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Timber.e(e,"请求失败")
                    }

                    override fun onResponse(call: Call, response: Response) {
                        Timber.fi("responseCode = ${response.code}")
                    }
                })
            }
        }
        Timber.fi("当前年份：${Calendar.getInstance().get(Calendar.YEAR)}")

        Timber.i("有修改设备的权限吗？${Settings.System.canWrite(this)}")
        if (!Settings.System.canWrite(this)) {
            startActivityForResult(Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS), 8888)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 8888) {
            if (Settings.System.canWrite(this)) {
                Timber.i("拥有写设置权限了")
            } else {
                Timber.i("没有写设置权限")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        handler.removeMessages(0)
        handler.sendEmptyMessage(0)
        binding.autoDateAndTimeCheckBox.isChecked = TimeUtil.isDateTimeAuto(this)
        binding.autoTimeZoneTimeCheckBox.isChecked = TimeUtil.isTimeZoneAuto(this)
        binding.use24HourCheckBox.isChecked = TimeUtil.is24HourFormat(this)
    }

    override fun onStop() {
        super.onStop()
        handler.removeMessages(0)
    }

    override fun handleMessage(msg: Message): Boolean {
        val timeFormat = if (TimeUtil.is24HourFormat(this)) "HH:mm:ss" else "hh:mm:ss a"
        val dateTimeFormat = "yyyy-MM-dd $timeFormat"
        val dateTime = DateFormat.format(dateTimeFormat, System.currentTimeMillis())
        binding.timeText.text = String.format("%s, %s", dateTime, TimeUtil.getTimeZoneId())
        handler.sendEmptyMessageDelayed(0, 1000)
        return true
    }
}